#include <QApplication>
#include <GL/glut.h>
#include <QtDebug>

#include <QByteArray>
#include <QDataStream>

#include "mpicalculator.h"
#include "windowglwidget.h"
#include "parafluidsph.h"

int main(int argc, char *argv[])
{
	int numNode;
	int currentNode;
	
	ParaFluid::MPI_start(numNode, currentNode)
	
	if(currentNode == 0)
	{
		QApplication app(argc, argv);
		glutInit(&argc, argv);
		app.exec();
		
		WindowGLWidget window;
		window.show();
	}
	else
	{
		ParaFluid::SPH sph;
		
		QByteArray data;
		int indexFirst;
		int indexLast;
		
		while(true)
		{
			
			for(int step = 0; step < 3; ++step)
			{
				
				// Receive SPH
				{
					char * buffer;
					int size;
					ParaFluid::MPI_receiveSPH(buffer, size);
					data = QByteArray(buffer, size);
					
					QDataStream stream(&data, QIODevice::ReadOnly);
					stream >> sph;
				}
				
				// Receive Index
				ParaFluid::MPI_receiveIndex(indexFirst, indexLast)
				
				// Send Result
				{
					data.clear();
					QDataStream stream(&data, QIODevice::WriteOnly);
					if(step == 0)
					{
						sph.parallelStepSlave1(stream, indexFirst, indexLast);
					}
					else if(step == 1)
					{
						sph.parallelStepSlave1(stream, indexFirst, indexLast);
					}
					else if(step == 2)
					{
						sph.parallelStepSlave1(stream, indexFirst, indexLast);
					}
					
					ParaFluid::MPI_sendIndex(indexFirst, indexLast)
					ParaFluid::MPI_sendResult(data.data(), data.size())
				}
			}
		}
	}
	
	ParaFluid::MPI_stop();
	
}
